<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar title="搜索页" left-arrow @click-left="$router.back()" />

    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!--  -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          $router.push({
            path: '/searchResult',
            query: { q: suggestion[index] },
          })
        "
      >
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "",
      suggestion: [],
      timeID: null,
    };
  },
  computed: {
    showList() {
      return this.suggestion.map((value) => {
        let reg = new RegExp(this.value, "ig");
        let res = value.replace(
          reg,
          (match) => `<span style='color:red;font-weight:700'>${match}</span>`
        );

        return res;
      });
    },
  },
  methods: {
    onSearch() {
      console.log(this.value);
      this.$router.push({ path: "/searchResult", query: { q: this.value } });
    },
    onInput() {
      clearTimeout(this.timeID);
      this.timeID = setTimeout(async () => {
        if (this.value == "") {
          this.suggestion = [];
          return;
        }
        console.log(this.value);
        let ret = await getSuggestion(this.value);
        this.suggestion = ret.data.data.options;
      }, 500);
    },
  },
};
</script>

<style>
</style>